<template>
  <main-card title="数据清洗" :loading="loading" :show-screen-space="false" :online-lab="true">
    <template #tool-btn>
      <a-button
        type="text"
        class="icon-only-btn"
        style="width: 36px; height: 36px"
        @click="taskListDrawerStore.changeTaskListOptions({ open: true })"
      >
        <i class="iconfont icon-tasklist-line" style="font-size: 18px"></i>
      </a-button>
      <a-button class="ml-8" type="primary" @click="router.push(`/data-clean/edit`)">
        <span class="text">创建任务</span>
      </a-button>
    </template>

    <div class="mb-48 fbc">
      <a-select v-model:value="pageForm.scheme" class="w-140" :options="schemeOptions" @change="getDataList({ offset: 1 })" />
      <a-select v-model:value="pageForm.status" class="ml-8 w-140" :options="typeOptions" @change="getDataList({ offset: 1 })" />
      <div class="flex-1"></div>
      <a-input
        v-model:value="pageForm.name"
        v-trim
        class="h-36"
        allow-clear
        placeholder="请输入名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      >
        <template #prefix> <i class="iconfont icon-search-line"></i> </template>
      </a-input>
    </div>

    <div class="page-table">
      <a-table
        :columns="tableColumns"
        :data-source="dataList"
        :pagination="false"
        :style="{ width: '100%' }"
        :custom-row="r => ({ onClick: () => handleToDetail(r.id) })"
        @change="tableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'scheme'">
            <div class="flex gap-4">
              <label-classification
                v-if="record.scheme === 1 || record.scheme === 4"
                :label-list="[{ labelId: '1', labelName: '去近似' }]"
              />
              <label-classification
                v-if="record.scheme === 2 || record.scheme === 4"
                :label-list="[{ labelId: '1', labelName: '去模糊' }]"
                :label-options-style="{ color: '#D61860', background: '#d6186014' }"
              />
            </div>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <div :class="['table__status', getTaskStatusItem(record.status)?.isError && 'error']">
              {{ getTaskStatusItem(record.status)?.name }}
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operate'">
            <a-dropdown placement="bottom" @click.stop>
              <a-button
                v-show="checkPermissions(record?.createType, record?.readOnly)"
                :data-share="record?.createType === 1"
                type="text"
                class="icon-only-btn"
                @click.stop
              >
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item class="menu-icon-item" @click="openRechristenForm(record.id, record.name)"> 重命名 </a-menu-item>
                  <a-menu-item class="menu-icon-item" @click="openDeleteTaskModal(record)"> 删除任务 </a-menu-item>
                  <a-menu-item class="menu-icon-item" @click="handleOpenShareModal(record)"> 分享 </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
          <template v-else-if="column.dataIndex === 'beforeRunTime'">
            {{ spliceTwoTimes(record.startTime, record.endTime) }}
          </template>
        </template>
      </a-table>
    </div>

    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card>

  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :loading="deleteConfirmDialogLoading"
    :confirm-name="currentDeleteTaskItem?.name"
    @ok="onOkDeleteTask"
  />
  <modal-form
    v-model:form-state="modelFormState"
    v-model:show="modelFormShow"
    :rules="modelFormRules"
    :loading="modelFormLoading"
    @ok="onModelFormSubmit"
  >
    <template #default="{ formState }">
      <a-form-item label="任务名称" name="name">
        <a-input v-model:value="formState.name" v-trim placeholder="请输入任务名称" :maxlength="200" />
      </a-form-item>
    </template>
  </modal-form>
  <task-list-drawer />

  <share-modal
    ref="shareModalRef"
    :submit-api="dataCleaningApi.share"
    :remove-user-api="dataCleaningApi.removeShareUser"
    :get-list-api="dataCleaningApi.getShareList"
  />
</template>

<script setup lang="ts">
  import { message, TableProps } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import GPagination from '@/components/GPagination/index.vue'
  import MainCard from '@/components/MainCard/index.vue'
  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { dataCleaningApi } from '@/services/api'
  import { spliceTwoTimes, validateBitLen, validateDirName } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'
  import { checkPermissions } from '@/utils/share'

  import TaskListDrawer from '../components/TaskListDrawer/index.vue'
  import { useTaskListDrawerStore } from '../components/TaskListDrawer/store'
  import { getTaskStatusItem, schemeOptions, taskStatusList } from '../options'

  type TaskItem = {
    endTime: null | string
    startTime: null | string
    createTime: string
    id: string
    status: string
    name: string
  }

  interface PageForm {
    name: string
    scheme: string
    status: string
    order: 'desc' | 'asc'
    columns: 'createTime' | ''
  }

  const router = useRouter()
  const taskListDrawerStore = useTaskListDrawerStore()

  type TableDataType = {
    key: string
    name: string
    age: number
    address: string
  }

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 240
      },
      {
        title: '清洗方式',
        dataIndex: 'scheme',
        width: 240
      },
      {
        title: '任务耗时',
        dataIndex: 'timeConsuming',
        width: 240
      },
      {
        title: '清洗状态',
        dataIndex: 'status',
        minWidth: 200
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 190,
        isSort: true
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        width: 190,
        isSort: true
      },
      {
        title: '操作',
        width: 80,
        dataIndex: 'operate'
      }
    ])
  )

  // 类型
  const typeOptions = [
    {
      label: '全部状态',
      value: ''
    },
    ...taskStatusList.map(it => ({
      label: it.title,
      value: it.status
    }))
  ]

  const { pageForm, dataList, loading, getDataList } = useList<PageForm, TaskItem>(dataCleaningApi.list, {
    name: '',
    status: '',
    scheme: '',
    columns: 'createTime',
    order: 'desc'
  })

  // 表格变化
  const tableChange: TableProps<TableDataType>['onChange'] = (pagination, filters, sorter: any) => {
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    pageForm.value.columns = sorter.field
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDataList({ offset: 1 })
  }
  getDataList()

  // 跳转到详情
  const handleToDetail = (id: string) => {
    router.push(`/data-clean/detail/${id}`)
  }

  /* 删除任务 */
  const currentDeleteTaskItem = ref<any>()
  const isDeleteDialogShow = ref(false)
  const openDeleteTaskModal = (item: any) => {
    currentDeleteTaskItem.value = item
    isDeleteDialogShow.value = true
  }
  // 确认删除
  const { loading: deleteConfirmDialogLoading, runAsync: runDelDataCleaning } = useRequest(dataCleaningApi.del)
  const onOkDeleteTask = async () => {
    await runDelDataCleaning({}, { urlParams: { id: currentDeleteTaskItem.value?.id || '' } })
    message.success('删除成功')
    isDeleteDialogShow.value = false
    getDataList()
  }

  /*----------------------------------------- 分享 --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: any) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }

  /* 重命名 */
  const modelFormShow = ref(false)
  const modelFormState = ref({
    id: '',
    name: ''
  })
  const openRechristenForm = (id: string, name: string) => {
    modelFormShow.value = true
    modelFormState.value.id = id
    modelFormState.value.name = name
  }
  const modelFormRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入任务名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ]
  }
  const { loading: modelFormLoading, runAsync: runEditDataCleaning } = useRequest(dataCleaningApi.edit)
  const onModelFormSubmit = async () => {
    await runEditDataCleaning(modelFormState.value, { isAddUid: true })
    message.success('编辑成功')
    modelFormShow.value = false
    getDataList()
  }
</script>

<style lang="less" scoped>
  .page-top {
    padding: 12px 0;
    // width: 100%;
    box-sizing: border-box;

    .pagetop-active {
      color: rgba(29, 32, 132, 1);
      background-color: transparent;
      border: none !important;
      box-shadow: none;
    }

    & > .ant-col {
      display: flex;
      align-items: center;
    }

    .ant-col + .ant-col {
      margin-left: 16px;
    }
  }

  .py-4 {
    padding: 4px 0;
  }
</style>
..
